package com.framework.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * object和map相互转换
 */
public class MapObjUtils {
    /**
     * 对象转map
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String,Object> objToMap(Object obj) throws IllegalAccessException {
        Map<String,Object> map=new HashMap<String, Object>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for(Field field:fields){
            field.setAccessible(true);
            if(field.getType()== Date.class){
                DateUtils.format((Date) field.get(obj),DateUtils.DATE_TIME_PATTERN);
            }else {

                map.put(field.getName(), field.get(obj));
            }
        }
        return map;
    }

    public static Map<String,Object> objToMapNoTranTime(Object obj) throws IllegalAccessException {
        Map<String,Object> map=new HashMap<String, Object>();
        Field[] fields = obj.getClass().getDeclaredFields();
        for(Field field:fields){
            field.setAccessible(true);
                map.put(field.getName(), field.get(obj));
        }
        return map;
    }


    /**
     * map转对象
     * @param map
     * @param clz
     * @return
     * @throws Exception
     */
    public static Object mapToObj(Map<String,Object> map,Class<?> clz) throws Exception{
        Object obj = clz.newInstance();
        Field[] declaredFields = obj.getClass().getDeclaredFields();
        for(Field field:declaredFields){
            int mod = field.getModifiers();
            if(Modifier.isStatic(mod) || Modifier.isFinal(mod)){
                continue;
            }
            field.setAccessible(true);
            field.set(obj, map.get(field.getName()));
        }
        return obj;
    }

}
